import { defineStore } from 'pinia';
import { ref, watch } from 'vue'
import type { TrackItem, UserDetailType, UserPlaylistType } from '@/services/type'
import { LoginStateApi, UserDetailApi, UserSongListApi } from '@/services/index'
export const useMusicStore = defineStore('listMusic', () => {
  const songs = ref<TrackItem[]>([])
  const song = ref<TrackItem>()
  const isSong = ref(false)
  const index =ref(-1)
  const audioContext = uni.createInnerAudioContext();
  isSong.value =! audioContext.paused
  const old = ref<TrackItem>()
  const userInfo = ref<UserDetailType>()
  const userStatusType = ref(false) // 用户登录状态
  const userId = ref(0) // 用户id
  const userSongList = ref<UserPlaylistType[]>([]) // 用户歌单列表
  watch(song,
    () => {
      index.value = songs.value.findIndex(vi => vi.id === song.value?.id)
    }
  )
  watch(index,  // 监听下标改变，更换当前曲
    () => {
      if (index.value >= songs.value.length ) index.value = songs.value.length-1
      if (index.value < 0) index.value = 0
      song.value = songs.value[index.value]
    },
    {
      // immediate: true
    }
  )

  // 获取登录状态
  const getUserStatus = async () => {
    try {
      const res = await LoginStateApi()
      console.log(res)
      userId.value = res.data.account.id // 获取用户id
      userStatusType.value = Boolean(res.data.profile) // 判断是否登录
    } catch (error) {
      console.log('获取用户状态失败', error)
    }
  }
  getUserStatus()

  // 获取用户详情
  const getUserDetail = async () => {
    try {
      const res = await UserDetailApi(userId.value)
      userInfo.value = res
    } catch (error) {
      console.log('获取用户详情失败',error)
    }
  }
  // 获取用户歌单
  const getUserSongList = async () => {
    try {
      const res = await UserSongListApi(userId.value)
      userSongList.value = res.playlist
    } catch (error) {
      console.log('获取用户歌单失败', error)
    }
  }
  // 当用户id改变时，获取用户信息
  watch(
    userId,
    () => {
      getUserDetail()
      getUserSongList()
    }
  )
  watch(
    userStatusType,
    () => {
      if (userStatusType.value) {
        getUserDetail()
        getUserSongList()
      } else {
        userInfo.value = undefined
        userSongList.value = []
        userInfo.value = undefined
        window.location.reload()
      }
    }
  )



  
  return {
    songs,
    song,
    isSong,
    audioContext,
    index,
    old,
    userInfo, // 用户信息
    userStatusType, // 用户登录状态
    userId, // 用户id
    userSongList, // 用户歌单列表
    getUserStatus, // 获取用户状态
    getUserDetail, // 获取用户详情
    getUserSongList // 获取用户歌单列表
  }
})
